"""
项目启动相关配置:
1. 数据库配置
2. redis配置
3. session配置, 为后续登陆保持做铺垫
4. 日志文件配置
5. CSRFProtect配置, 为了对,'POST','PUT','DISPATCH','DELETE'做保护
6. 迁移配置


"""""
import logging
import random
from datetime import datetime, timedelta

from flask import Flask,session,current_app

from info import create_app
from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand
from info import db,models
from info.models import User

app=create_app('develop')

manager=Manager(app)

Migrate(app,db)
manager.add_command("db",MigrateCommand)

#参数1：表示
@manager.option('-p', '--password', dest='password')
@manager.option('-u', '--username', dest='username')
def create_superuser(username,password):
    admin=User()

    # 2.设置属性

    admin.nick_name=username
    admin.mobile=username
    admin.password=password
    admin.is_admin=True

    # 3.保存到数据库

    try:
        db.session.add(admin)
        db.session.commit
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"
    return "创建成功"

@manager.option('-t', '--test', dest='test')
def add_test_user(test):
    # 定义用户容器
    user_list = []

    # for循环创建1000个用户
    for i in range(0, 1000):
        # 创建用户对象,设置属性
        user = User()
        user.nick_name = "老王%d" % i
        user.mobile = "138%08d" % i
        user.password_hash = "pbkdf2:sha256:50000$2uwMQz1Q$6273098e3b63d262f371b9e420c42c7d2871365970ce0939e38ca279bc3913a0"

        # 设置用户近31天的登陆时间
        user.last_login = datetime.now() - timedelta(seconds=random.randint(0, 3600 * 24 * 31))

        # 添加到容器中
        user_list.append(user)

    # 添加到数据库
    try:
        db.session.add_all(user_list)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return "添加失败"

    return "添加成功"


if __name__ == '__main__':
    manager.run()
